#include "BulletFactory.h"
#include "Application.h"
#include "Helpers.h"

cat::BulletFactory::BulletFactory(void)
{
}


cat::BulletFactory::~BulletFactory(void)
{
	DELETE_LIST_ITEMS(_activeBullets, cat::Bullet);
	DELETE_LIST_ITEMS(_deadBullets, cat::Bullet);
}


void cat::BulletFactory::create(double x, double y, double direction)
{
	cat::Bullet* createdBullet = NULL;
	if(!_deadBullets.empty())
	{
		createdBullet = _deadBullets.back()->Initialize(x, y, direction);
		_deadBullets.pop_back();
	}
	else
	{
		createdBullet = new Bullet(x, y, direction);
	}

	_activeBullets.push_back(createdBullet);
}

void cat::BulletFactory::think(void)
{
	std::list<cat::Bullet*>::iterator it = _activeBullets.begin();
	while(it != _activeBullets.end())
	{
		cat::Bullet* current = *it;
		if(current->getRemaingFrames() > 0)
		{
			current->Think();
			++it;
		}
		else
		{
			// bullet has finished its life cycle
			_deadBullets.push_back(current);
			_activeBullets.erase(it++);
		}
	}
}

void cat::BulletFactory::draw()
{
	sf::RenderWindow& window = cat::Application::current().getWindow();

	std::list<cat::Bullet*>::iterator it = _activeBullets.begin();
	for(; it != _activeBullets.end(); ++it)
	{
		(*it)->Draw(window);
	}
}